<template>
  <q-page class="q-pa-md">
    <div class="row items-center">
      <div class="q-pb-md text-h5">
        {{ pageTitle }}
        <span class="text-subtitle1">列表</span>
      </div>
      <q-space></q-space>
      <search-bar-toggle-btn v-model="searchBarVisibility"></search-bar-toggle-btn>
    </div>
    <div class="q-pa-sm shadow-2 q-mb-md items-center" v-show="searchBarVisibility">
      <div class="row q-col-gutter-sm">
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">bill of lading</div>
          <div class="col-8">
            <easy-input v-model="fpsReq.billOfLading" @focus="fx.ui.select" @keyup.enter="loadListData(2)"
              :readonly="listDataLoadingState">
            </easy-input>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">OB合同号</div>
          <div class="col-8">
            <easy-input v-model="fpsReq.contractNo" @focus="fx.ui.select" @keyup.enter="loadListData(2)"
              :readonly="listDataLoadingState">
            </easy-input>
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">创建日期从</div>
          <div class="col-8">
            <easy-input v-model="fpsReq.createDtBeg" use-date-picker append-icon-show :readonly="listDataLoadingState" />
          </div>
        </div>
        <div class="col-12 col-sm-6 col-md-4 col-lg-3 row q-col-gutter-sm">
          <div class="col-4 text-right searchbar-label">创建日期至</div>
          <div class="col-8">
            <easy-input v-model="fpsReq.createDtEnd" use-date-picker append-icon-show :readonly="listDataLoadingState" />
          </div>
        </div>
        <div class="col-shrink row q-col-gutter-sm">
          <div class="col">
            <q-toggle v-model="fpsReq.isSuccess" :disable="listDataLoadingState" @update:model-value="loadListData(2)"
              dense toggle-indeterminate class="q-ma-xs" label="是否成功"/>
          </div>
        </div>
      </div>
      <div class="row q-pt-sm">
        <div class="q-mr-sm">
          <q-btn :disable="listDataLoadingState" @click="loadListData(2)" color="primary" icon="search" label="查询" />
        </div>
      </div>
    </div>
    <div class="shadow-2">
      <q-table @request="fpsAssist.onDataTableRequest" :rows="$d.tableData" :columns="fpsInfo.columnsInfo"
        separator="cell" row-key="id" v-model:pagination="fpsInfo.paginationInfo" :visible-columns="fpsInfo.visibleColumns"
        dense flat :hide-pagination="true" :loading="listDataLoadingState" color="primary" binary-state-sort hide-selected-banner
        @row-dblclick="(evt,row)=>{fpsNav.gotoDetail(row.id)}" v-model:selected="$d.selectedItems" selection="multiple">
        <template v-slot:top="props">
          <!--功能按钮-->
          <div class="q-gutter-sm">
            <q-btn @click="onImportsByExcel" color="primary" icon="fas fa-file-import" label="OB合同导入" />
            <q-btn @click="toDocument" color="primary" label="转业务单证" :disable="$d.selectedItems.length === 0" />
            <q-btn @click="updateCbCode" color="primary" label="更新账册代码" :disable="$d.selectedItems.length === 0" />
          </div>
          <!--填充所有剩余空间-->
          <q-space />
          <table-col-options-cfg v-model:table-columns="fpsInfo.columnsInfo"
            v-model:visible-columns="fpsInfo.visibleColumns"
            @update-col-options-for-save="fpsAssist.saveColOptions">
          </table-col-options-cfg>
          <q-btn flat dense :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
            :title="props.inFullscreen ? '退出全屏' : '全屏显示'" @click="props.toggleFullscreen" class="q-ml-sm"
            :ripple="false" />
        </template>
        <!--操作列插槽-->
        <template v-slot:body-cell-operation="props">
          <q-td :props="props" auto-width>
            <q-btn color="primary" label="查看" class="q-mr-xs btn-in-row" :dense="true"
              @click="evt => fpsNav.gotoDetail(props.row.id, evt)" />
          </q-td>
        </template>
        <template v-slot:body-cell-isSuccess="props">
          <q-td :props="props" auto-width>
            <q-badge :color="props.row.isSuccess?'positive':'grey-6'"
              :label="props.row.isSuccess ? '是' : '否'" />
          </q-td>
        </template>
        <template v-slot:no-data>
          <div class="full-width items-center justify-center row">
            <q-icon name="error_outline" />
            无数据
            <q-btn flat icon="refresh" :loading="listDataLoadingState"
              :disable="listDataLoadingState" dense title="刷新" size="sm" class="q-ml-sm" @click="loadListData"></q-btn>
          </div>
        </template>
        <template v-slot:bottom>
          <paging-bar :pageNo="fpsReq.pageNo" :pageSize="fpsReq.pageSize" :totalAmount="fpsInfo.totalAmount"
            @pagesize-changed="fpsAssist.onPageSizeChanged" @go-to-page="fpsNav.gotoPage"
            :loading-state="listDataLoadingState" />
        </template>
      </q-table>
    </div>

    <!--批量导入-->
    <q-dialog transition-hide="none" transition-show="none" v-model="showingImportDlg">
      <q-card style="max-width: 400px; width: 100%">
        <q-card-section class="q-pa-sm">
          <div class="text-h6">OB合同导入
            <a @click="fx.nw.downloadFile('/project/mhlbc/res/download/mhl-ims-ob-contract-import-template.xlsx','',false)"
                class="text-body2" href="javascript:void(0)">导入模板下载</a></div>
        </q-card-section>
        <q-separator />
        <!--错误提示-->
        <q-banner class="text-white bg-red q-mt-sm q-mx-sm" dense inline-actions v-if="errorMessageForImport">
          {{ errorMessageForImport }}
          <template v-slot:action>
            <q-btn @click="errorMessageForImport = ''" dense flat icon="close" size="sm" />
          </template>
        </q-banner>
        <div class="q-pa-sm">
          <div class="row justify-between">
            <input ref="asnListExcelFileInput" type="file" />
          </div>
        </div>
        <q-separator class="separator" />
        <q-card-actions align="right">
          <q-btn @click="importExcel" color="primary" label="确定" />
          <q-btn color="primary" label="取消" outline unelevated v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <!--更新账册代码-->
    <q-dialog transition-hide="none" transition-show="none" v-model="updateCbCodeDlg">
      <q-card style="max-width: 300px; width: 100%">
        <q-card-section class="q-pa-sm">
          <div class="text-h6">更新账册代码</div>
        </q-card-section>
        <q-separator />
        <!--错误提示-->
        <q-banner class="text-white bg-red q-mt-sm q-mx-sm" dense inline-actions v-if="errorMessageForCbCode">
          {{ errorMessageForCbCode }}
          <template v-slot:action>
            <q-btn @click="errorMessageForCbCode = ''" dense flat icon="close" size="sm" />
          </template>
        </q-banner>
        <div class="q-pa-sm">
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <span>账册代码</span>
              <simple-filter-select
                  :options="$d.cbCodeDropdownList" :use-filter="false"
                  v-model="$d.cbCode" :auto-select-single-option="true" />
            </div>
          </div>
        </div>
        <q-separator class="separator" />
        <q-card-actions align="right">
          <q-btn @click="doUpdateCbCode" color="primary" label="确定" :disable="!$d.cbCode"  />
          <q-btn color="primary" label="取消" outline unelevated v-close-popup />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script lang="ts">
export default {
  name: 'ObContractList'
}

</script>

<script lang="ts" setup>

import {useFpsHelper} from '@njt/foundation/hooks/fpsHelper'
import {useTitleHelper} from '@njt/foundation/hooks/titleHelper'
import {reactive, ref} from 'vue'
import {ColumnInfo} from '@njt/foundation/defs/comm'
import {GetObContractListReq, GetObContractListResp, ObContractInfo} from 'src/defs/ims/obContract'
import _ from 'lodash'

const pageTitle = 'OB合同'
useTitleHelper(pageTitle)

const $d = reactive({
  tableData: [] as ObContractInfo[],
  selectedItems: [] as ObContractInfo[],
  cbCode: null as string | null,
  cbCodeDropdownList: ['D1288', 'L2588']
})

let fpsReq: GetObContractListReq = reactive({
  billOfLading: null,
  contractNo: null,
  createDtBeg: null,
  createDtEnd: null,
  isSuccess: null,
  pageNo: 1,
  pageSize: 40,
  isDescending: false,
  orderBy: null
})

const columnsDefine: ColumnInfo[] = [
  {
    label: '操作',
    name: 'operation',
    field: 'operation',
    align: 'left',
    defVisible: true,
    defOrder: 1,
  },
  {
    label: '序号',
    name: 'id',
    field: 'id',
    align: 'left',
    defVisible: true,
    sortable: true,
    defOrder: 2,
  },
  {
    label: 'bill of lading',
    name: 'billOfLading',
    field: 'billOfLading',
    align: 'left',
    defVisible: true,
    defOrder: 3,
  },
  {
    label: '合同号',
    name: 'contractNo',
    field: 'contractNo',
    align: 'left',
    defVisible: true,
    defOrder: 4,
  },
  {
    label: '是否成功',
    name: 'isSuccess',
    field: 'isSuccess',
    align: 'left',
    defVisible: true,
    defOrder: 5,
  },
  {
    label: '错误信息',
    name: 'backMsg',
    field: 'backMsg',
    align: 'left',
    defVisible: true,
    defOrder: 6,
    format: (val: string | null) => {
      return (val && val.length>130)?`${val.slice(0, 129)}...`:val
    }
  },
  {
    label: '创建人',
    name: 'createP',
    field: 'createP',
    align: 'left',
    defVisible: true,
    defOrder: 7,
    format: (val: string,row: ObContractInfo) => $f.fmt.userDisp(val, row.createPn)
  },
  {
    label: '创建时间',
    name: 'createDt',
    field: 'createDt',
    align: 'left',
    defVisible: true,
    defOrder: 8,
    format: (val: string) => $f.fmt.dtFmtFullNoSec(val)
  },
]

let listDataLoadingState = ref(false)
const loadListData = function (resetFpsReq?: number) {
  if (resetFpsReq) {
    if (resetFpsReq >= 1) {
      fpsReq.pageNo = 1
    }
    if (resetFpsReq >= 2) {
      fpsReq.orderBy = ''
      fpsReq.isDescending = false
    }
  }
  listDataLoadingState.value = true
  $f.axios
    .get<GetObContractListResp>('/mhlbc/ims/get-ob-contract-list', {params: fpsReq})
    .then((resp) => {
      if (resp.data.createDtBeg)
        resp.data.createDtBeg = $f.fmt.dtFmtDateOnly(resp.data.createDtBeg)
      if (resp.data.createDtEnd)
        resp.data.createDtEnd = $f.fmt.dtFmtDateOnly(resp.data.createDtEnd)
      fpsAssist.handleGenericFpsResp(resp.data)
      $d.tableData = resp.data.obContractInfos
      fpsAssist.saveFpsReq(fpsReq)
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      listDataLoadingState.value = false
    })
}

const {
  fpsInfo,
  fpsNav,
  fpsAssist,
  searchBarVisibility
} = useFpsHelper('/ims/ob-contract',
  '/ims/ob-contract/detail',
  null,
  null,
  fpsReq,columnsDefine,
  null,
  loadListData
)

let showingImportDlg = ref(false)
let errorMessageForImport = ref('')
// 批量导入按钮
const onImportsByExcel = function () {
  showingImportDlg.value = true
  errorMessageForImport.value = ''
}
let importExcelState = ref(false)
let asnListExcelFileInput = ref()
// 批量导入确定
const importExcel = function () {
  importExcelState.value = true
  let formData = new window.FormData()
  formData.append('dataFile', asnListExcelFileInput.value.files[0])
  $f.axios
      .post('/mhlbc/ims/import-ob-contract', formData)
      .then(() => {
        showingImportDlg.value = false
        $f.ui.showNotifySucceeded('导入成功')
        loadListData(2)
      })
      .catch((err) => {
        if (err.response?.data?.errorList?.length) {
          showingImportDlg.value = false
          $f.ui.showErrorListDlg(err.response.data)
        } else {
          errorMessageForImport.value = $f.getAxiosErrMsg(err)
        }
      })
      .finally(() => {
        importExcelState.value = false
      })
}

// 转业务单证
const toDocument = () => {
  void $f.ui.messageBox({
    caption: '操作确认',
    text: '确定要转业务单证吗?',
    icon: 'Question',
    buttons: 'OkCancel',
    delayClose: true
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios
          .post('/mhlbc/ims/send-ob-contract-for-order',_.map($d.selectedItems, 'id'))
          .then((resp) => {
            $f.ui.closeMsgBox()
            loadListData()
          })
          .catch((err) => {
            $f.ui.closeMsgBox()
            if (err.response?.data?.errorList?.length) {
              $f.ui.showErrorListDlg(err.response.data)
            } else {
              void $f.ui.messageBox({
                caption: '操作失败',
                text: $f.getAxiosErrMsg(err),
                icon: $f.getAxiosErrIcon(err),
                buttons: 'Close',
              })
            }
          })
    }
  })
}

let updateCbCodeDlg = ref(false)
let errorMessageForCbCode = ref('')
const updateCbCode = () => {
  $d.cbCode = null
  errorMessageForCbCode.value = ''
  updateCbCodeDlg.value = true
}
const doUpdateCbCode = () => {
  let params = {
    ids: _.map($d.selectedItems, 'id'),
    cbCode: $d.cbCode
  }
  $f.axios.post('/mhlbc/ims/update-ob-contract-cb-code', params)
      .then(() => {
        $f.ui.showNotifySucceeded('更新成功')
        updateCbCodeDlg.value = false
        loadListData()
      })
      .catch((err) =>{
        if (err.response?.data?.errorList?.length) {
          updateCbCodeDlg.value = false
          $f.ui.showErrorListDlg(err?.response?.data)
        } else {
          errorMessageForCbCode.value = $f.getAxiosErrMsg(err)
        }
      })
}


const fx = $f
</script>

<style scoped>

</style>
